package module.modbus.tcp;

import common.MonitorHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Random;

public class TcpStartThread implements Runnable {


     public static boolean isRunning = true;

    private ModbusTcp modbusTcp;

    private int count = 0;

    private Logger logger = LoggerFactory.getLogger(TcpStartThread.class);

    public TcpStartThread(ModbusTcp modbusTcp) {
        this.modbusTcp = modbusTcp;
    }

    @Override
    public void run() {
        System.out.println("线程已经启动~~~~~~~~~~开始运行");
        int[] slaveId = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int[] methodCode = new int[]{3, 6, 16};
        Random random = new Random();
        while (TcpStartThread.isRunning) {
            count++;
            logger.info("第【"+count+"】次请求！");
            MonitorHelper.pause(500);
            int slave = random.nextInt(slaveId.length);
            int code = random.nextInt(methodCode.length);
            short[] data = null;
            if (methodCode[code] == 6) {
                data = new short[1];
                data[0] = (short) random.nextInt(Short.MAX_VALUE);
            } else if (methodCode[code] == 3) {
                data = new short[1];
                data[0] = (short) random.nextInt(10);
            } else if (methodCode[code] == 16) {
                data = new short[10];
                for (int i = 0; i < 10; i++) {
                    data[i] = (short) random.nextInt(Short.MAX_VALUE);
                }
            }

            modbusTcp.send(slaveId[slave], methodCode[code], 0, data);
            }
        System.out.println("是否运行:"+TcpStartThread.isRunning);
        try {
            modbusTcp.getSocket().close();
            System.out.println("socket已经关闭");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
